﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using DSTVKPOS;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for SummaryForm.xaml
    /// </summary>
    /// 
    public partial class DSTVKPOS : DocumentBase
    {
        #region=============Properties=======================
        public OracleConnection OracleDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        DSTVKPOSData m_VK;
        public DataSet setResult;
        private DataRow dwUI;
        DSTVKPOSReport m_rpt;
        ExcelX.ExcelLib.ExcelAgent m_exAgent;
        DataRow dwBSFARB, dwBHSATZ;
        string UserID = "";
        string ART = "";
        DataRow dwWAFARBEN;
        #region==========CollectionViewSource=================
        SETDSTVKPOS setvk
        {
            get
            {
                return (SETDSTVKPOS)this.FindResource("SETVK");
            }
        }
        DataSet setWAART = new DataSet();
        CollectionViewSource vwWASTAMM
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwWASTAMM");
            }
        }
        CollectionViewSource vwWAPROF
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwWAPROF");
            }
        }
        CollectionViewSource vwVKPOS
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKPOS");
            }
        }
        CollectionViewSource vwVKKOPF
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKKOPF");
            }
        }
        CollectionViewSource vwWAFARBEN
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwWAFARBEN");
            }
        }
        CollectionViewSource vwWDECK
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwWDECK");
            }
        }
        CollectionViewSource vwVKKANGE
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKKANGE");
            }
        }
        CollectionViewSource vwVKKBEST
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKKBEST");
            }
        }
        CollectionViewSource vwVKKIVDI
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKKIVDI");
            }
        }
        CollectionViewSource vwVKKIVVT
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKKIVVT");
            }
        }
        CollectionViewSource vwVKKLIEF
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKKLIEF");
            }
        }
        CollectionViewSource vwVKKLVOR
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKKLVOR");
            }
        }
        CollectionViewSource vwVKKRECH
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKKRECH");
            }
        }
        CollectionViewSource vwVKPANGE
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKPANGE");
            }
        }
        CollectionViewSource vwVKPBEST
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKPBEST");
            }
        }
        CollectionViewSource vwVKPIVDI
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKPIVDI");
            }
        }
        CollectionViewSource vwVKPIVVT
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKPIVVT");
            }
        }
        CollectionViewSource vwVKPLIEF
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKPLIEF");
            }
        }
        CollectionViewSource vwVKPLVOR
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKPLVOR");
            }
        }
        CollectionViewSource vwVKPRECH
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwVKPRECH");
            }
        }
        #endregion
        DataSet setVKPOS = new DataSet();
        DataSet setUIWAART = new DataSet();
        BackgroundWorker bgWorker, bgWorkerOn;
        MessageInfo msg;
        GreigeMasterData m_GM;
        private string color;
        DataRow dwWDECK = null;
        private string finish;
        int procecessed = 0;
        int total = 0;
        private DataRow dwVKPOS;
        bool IsApproved = false;

        private DataRow dwWASTAMM;

        public TextBox TxtUserID
        {
            get
            {
                return ((TextBox)this.FindName("txtUserID"));
            }
        }
        public DSTVKPOS()
        {
            InitializeComponent();
            this.Name = "DSTVKPOS";
            this.Title = "生产指令表";
            ZoneAccount.Visibility = Visibility.Hidden;
            ZoneAuditing.Visibility = Visibility.Hidden;
            ZoneFTP.Visibility = Visibility.Hidden;
            ZoneOrder.Visibility = Visibility.Hidden;
        } 
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    base.SetUp(dicParamater);
                    InitializeComponent();
                    this.dicParamater = dicParamater;
                    OracleDB = (OracleConnection)dicParamater["OracleDB"];
                    proxy = (IntexReptServBLClient)dicParamater["proxy"];
                    m_VK = new DSTVKPOSData(OracleDB, proxy);
                    m_GM = new GreigeMasterData(OracleDB, proxy);
                    string memberv9 = m_VK.GetMemberV9("DST");
                    string Admn = m_VK.GetAdministration("DST");
                    MemberV9.Text = memberv9;
                    Administration.Text = Admn;

                    #region============TESTINGDATA================
                    /*txtVKPAUFKRS.Text = "C0";
                   txtVKPAUFLFD.Text = "100227";
                    txtVKPAUFKRS.Text = "A1";
                    txtVKPAUFLFD.Text = "000007";

                    txtUserID.Text = (string)dicParamater["User"];
                    txtPassword.Password = (string)dicParamater["Pwd"];
                    */
                    #endregion
                    expWS.IsExpanded = false;
                    expTech.IsExpanded = false;
                    btnReport.IsEnabled = true;
                    btnPrintPreview.IsEnabled = true;
                    btnGetVKPOS.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnLogIn_Click(object sender, RoutedEventArgs e)
        {
            ZoneAccount.Visibility = Visibility.Hidden;
            ZoneAuditing.Visibility = Visibility.Hidden;
            ZoneFTP.Visibility = Visibility.Hidden;
            ZoneOrder.Visibility = Visibility.Hidden;
            string Mandant = txtMANDANT.Text.ToUpper();
            string userID = m_VK.Left(txtUserID.Text.ToUpper() + "        ", 8);
            System.Security.SecureString SPassword = txtPassword.SecurePassword;
            txtLogIn.Background = new SolidColorBrush(Colors.Yellow);
            DataSet setResult = m_VK.LogIn(Mandant, userID, SPassword);
            if (setResult.Tables.Count > 0)
            {
                DataRow dwUser = setResult.Tables[0].Rows[0];
                txtSPRACHKZ.Text = dwUser["HRSPRKZ"].ToString();
                UserID = userID;
                m_VK.UserID = userID;
                this.UserID = userID;

                m_VK.WorkingDate = DateTime.Now.Year.ToString() + m_VK.Right("00" + DateTime.Now.Month.ToString(), 2)
                    + m_VK.Right("00" + DateTime.Now.Day.ToString(), 2);
                m_VK.MANDANT = Mandant;
                m_VK.SPRACHKZ = txtSPRACHKZ.Text.Trim();
                /*this.txtLogIn.Text = DateTime.Now.ToLocalTime().ToString() + ": " + userID + "已登录";
                txtLogIn.Background = new SolidColorBrush(Colors.Green);*/
                m_GM = new GreigeMasterData(OracleDB, proxy, UserID);
                expLog.IsExpanded = false;
                //expLog.Visibility = Visibility.Hidden;
                btnReport.IsEnabled = true;
                btnPrintPreview.IsEnabled = true;
                btnGetVKPOS.IsEnabled = true;
                btnDistribute.IsEnabled = false;
                IsBelongs2V9.IsChecked = false;
                IsOnAuditing.IsChecked = false;
                IsSendForAuditing.IsChecked = true;
                IsBelongs2Admin.IsChecked = false;
                ZoneOrder.Visibility = Visibility.Visible;
                ZoneAccount.Visibility = Visibility.Visible;
                if (MemberV9.Text.Contains(userID.Trim() + ";"))
                {
                    btnDistribute.IsEnabled = true;
                    IsBelongs2V9.IsChecked = true;
                    IsOnAuditing.IsChecked = true;
                    IsSendForAuditing.IsChecked = false;
                    this.txtLogIn.Text = DateTime.Now.ToLocalTime().ToString() + ": " + userID + "开始审单";
                    ZoneAccount.Visibility = Visibility.Hidden;
                    ZoneAuditing.Visibility = Visibility.Visible;
                    ZoneFTP.Visibility = Visibility.Hidden;
                }
                if (Administration.Text.Contains(userID.Trim() + ";"))
                {
                    ZoneAccount.Visibility = Visibility.Hidden;
                    ZoneAuditing.Visibility = Visibility.Hidden;
                    ZoneFTP.Visibility = Visibility.Visible;
                    ZoneOrder.Visibility = Visibility.Hidden;
                    IsBelongs2Admin.IsChecked = true;
                    this.txtLogIn.Text = DateTime.Now.ToLocalTime().ToString() + ": " + userID + "开始设置FTP信息";
                }
                else
                {
                    btnLogFTP_Click(null, null);
                }
                EventDispatcher.Instance.RaiseStatus(txtLogIn.Text, StatusEventType.UserLogIn);
            }
        }
        public void btnLogFTP_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SetUpFtp();
                string ftpsite = txtFTPSite.Text.Trim();
                string ftpport = txtFTPPort.Text.Trim();
                string ftpuser = txtFTPUser.Text.Trim();
                CheckFtp(ftpsite, ftpport, ftpuser, txtFTPPwd,IsBelongs2Admin.IsChecked==true);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                MessageBox.Show("FTP登录信息有误。请联系你们的破管理员。");
            }
            finally
            {
                ftpClient.Close();
            }
        }
        private void MergetListData()
        {
            try
            {
                setvk.Merge(setVKPOS);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        #endregion

        #region==========FABRIC======================
        private void btnReport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string PrintType = "JustExcel";
                GenerateReport(PrintType);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnPrintPreview_Click(object sender, RoutedEventArgs e)
        {
            string PrintType = "OpenExcel";
            GenerateReport(PrintType);
        }
        private void btnDistribute_Click(object sender, RoutedEventArgs e)
        {
            string PrintType = "OpenExcel";
            GenerateReport(PrintType, true);
        }
        public void GenerateReport(string PrintType, bool isapproved = false)
        {
            try
            {
                DSTVKPOSData m_DX = new DSTVKPOSData(dicParamater);
                DSTVKPOSReport m_rpt = new DSTVKPOSReport(dicParamater);
                m_rpt.dsSource = setvk;
                m_rpt.PrintType = PrintType;
                m_rpt.exAgent = m_DX.exAgent;
                m_rpt.OracleDB = this.OracleDB;
                m_rpt.proxy = this.proxy;
                m_rpt.IsApproved = isapproved;
                m_rpt.ftpClient = ftpClient;
                if (IsOnAuditing.IsChecked == true)
                {
                    m_rpt.IsOnAuditing = true;
                }
                if (IsSendForAuditing.IsChecked == true)
                {
                    m_rpt.IsSendForAuditing = true;
                }
                
                m_rpt.Shareroot = txtShareroot.Text.Trim();
                m_rpt.WriteExcelReport(PrintType);
                //btnReport.IsEnabled = false;
                //btnPrintPreview.IsEnabled = false;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                setvk.Clear();
                setvk.AcceptChanges();
                MergetListData();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void QueryWASTAMM(DataRow dwVKPOS, bool refresh = false)
        {
            try
            {
                refresh = true;
                DataRow dwVAFARBEN = null;
                setUIWAART = new DataSet();
                //判断对应的WDECK是否已经有生产物料，否则用户在这里指定
                //如果已经有，则使用生产物料进行查询产品信息 
                var query = from dwTemp in setvk.WDECK.AsEnumerable()
                            where dwTemp["WDAUFKRS"].ToString() == dwVKPOS["VKPAUFKRS"].ToString()
                            && dwTemp["WDAUFLFD"].ToString() == dwVKPOS["VKPAUFLFD"].ToString()
                            && dwTemp["WDAUFPOS"].ToString() == dwVKPOS["VKPAUFPOS"].ToString()
                            select dwTemp;
                foreach (DataRow dwTemp in query)
                {
                    dwWDECK = dwTemp;
                }
                string WDPRART = "", WDPRVAR = "";
                if (!refresh)
                {
                    if (dwWDECK != null)
                    {
                        WDPRART = dwWDECK["WDPRART"].ToString();
                        WDPRVAR = dwWDECK["WDPRVAR"].ToString();
                    }
                }
                if (WDPRART.Trim() != "")
                {
                    setResult = m_VK.QueryWDART(WDPRART, WDPRVAR);
                    setUIWAART.Merge(setResult);
                    return;
                }

                setResult = m_VK.QueryVA0710(dwVKPOS);
                if (!setResult.Tables.Contains("VAFARBEN"))
                    return;
                if (setResult.Tables["VAFARBEN"].Rows.Count == 0)
                    return;
                dwVAFARBEN = setResult.Tables["VAFARBEN"].Rows[0];
                setResult = m_VK.QueryWDART(dwVAFARBEN);
                setUIWAART.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                dgWASTAMM.DataContext = setUIWAART;

                ICollectionView cv = CollectionViewSource.GetDefaultView(dgWASTAMM.ItemsSource);
                if (cv != null)
                {
                    cv.MoveCurrentToFirst();
                    if (dgWASTAMM.Items.Count > 0)
                    {
                        dgWASTAMM.SelectedIndex = 0;
                    }
                }
            }
        }
        #endregion
        private void dgVKPOS_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            DataSet setResult = new DataSet();
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;
                    dwVKPOS = drv.Row;
                }
                if (dwVKPOS == null)
                    return;
                #region==========VK07==================
                /*
                string KRS = dwVKPOS["VKPAUFKRS"].ToString();
                string LFD = dwVKPOS["VKPAUFLFD"].ToString();
                string POS = dwVKPOS["VKPAUFPOS"].ToString();
                string TXTISIND = KRS + LFD + POS + "BEST";
                var queryPBEST = from dwTemp in setvk.TXTKON.AsEnumerable()
                                 where dwTemp["TXTIPIND"].ToString().Trim().Contains(TXTISIND)
                                 select dwTemp;
                if (queryPBEST.Count() > 0)
                {
                    setvk.VKPBEST.Merge(queryPBEST.CopyToDataTable());
                }
                TXTISIND = KRS + LFD + "000" + "BEST";
                var queryKBEST = from dwTemp in setvk.TXTKON.AsEnumerable()
                                 where dwTemp["TXTIPIND"].ToString().Contains(TXTISIND)
                                 select dwTemp;
                if (queryKBEST.Count() > 0)
                {
                    setvk.VKKBEST.Merge(queryKBEST.CopyToDataTable());
                }
                if (vwVKKBEST.View != null)
                {
                    vwVKKBEST.View.MoveCurrentToFirst();
                }
                if (vwVKPBEST.View != null)
                {
                    vwVKPBEST.View.MoveCurrentToFirst();
                }
                */
                #endregion
                QueryWASTAMM(dwVKPOS);
                procecessed++;
                EventDispatcher.Instance.RaiseStatus("查询进行中" + procecessed + "/" + total, StatusEventType.RunningProgress);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnGetVKPOS_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                setvk.Clear();
                DataSet setResult = new DataSet();
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    DataRow dwVKKOPF = setvk.VKKOPF.NewVKKOPFRow();
                    dwVKKOPF["VKKMANDANT"] = "00";
                    dwVKKOPF["VKKAUFKRS"] = m_VK.Left(txtVKPAUFKRS.Text + "  ", 2);
                    dwVKKOPF["VKKAUFLFD"] = m_VK.Right("0000000" + txtVKPAUFLFD.Text, 6);
                    setResult = m_VK.GetData(dwVKKOPF);
                    setvk.Merge(setResult);
                    if (vwVKPOS.View != null)
                        vwVKPOS.View.MoveCurrentToFirst();
                    total = setvk.VKPOS.Rows.Count;
                    EventDispatcher.Instance.RaiseStatus("查询开始", StatusEventType.StartProgress);
                    using (new LongOperation(this, "读取符合条件的记录"))
                    {
                        while (!vwVKPOS.View.IsCurrentAfterLast)
                        {
                            vwVKPOS.View.MoveCurrentToNext();
                        }
                    }
                    EventDispatcher.Instance.RaiseStatus("查询结束", StatusEventType.StopProgress);
                    if (vwVKKOPF.View != null)
                    {
                        vwVKKOPF.View.MoveCurrentToFirst();
                        StartDocumentApproval();
                    }
                }
                btnReport.IsEnabled = true;
                btnPrintPreview.IsEnabled = true;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
            }
        }
        private void dgWASTAMM_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            DataSet setWAART = new DataSet();
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;
                    dwWASTAMM = drv.Row;
                }
                if (dwWASTAMM == null)
                    return;
                if (dwWDECK == null)
                    return;
                dwWDECK["WDPRART"] = dwWASTAMM["WAART"];
                dwWDECK["WDPRVAR"] = dwWASTAMM["WAVAR"];
                m_VK.UpdateWDECK(dwWDECK, dwWASTAMM);
                dwWAFARBEN = setvk.WAFARBEN.NewWAFARBENRow();
                dwWAFARBEN["WAFART"] = dwWASTAMM["WAART"];
                dwWAFARBEN["WAFVAR"] = dwWASTAMM["WAVAR"];
                string color = dwWDECK["WDFARBE"].ToString();
                string finish = dwWDECK["WDBESCHICH"].ToString();
                setResult = m_GM.GetData(dwWAFARBEN, color, finish,"C");
                setWAART.Merge(setResult);
                setvk.Merge(setResult);
                if (setResult.Tables.Contains("TXTKON"))
                {
                    setvk.Merge(setResult.Tables["TXTKON"]);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
        private void cmdReferesh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                QueryWASTAMM(dwVKPOS, true);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void StartDocumentApproval()
        {
            try
            {
                return;
               
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
    }
}
